package com.demo.common.redis.pubsub;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 在容器启动后处理 redis 的消息订阅对象 （pub/sub方式）
 * </p>
 *
 * @author molong
 * @date 2022/6/22
 */
public class PubSubApplicationStartedEvent implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        RedisMessageListenerContainer container = SpringUtil.getBean(RedisMessageListenerContainer.class);
        //获取序列化器
        RedisSerializer<?> serializer = SpringUtil.getBean(RedisSerializer.class);

        Map<String, BaseSubMessageDelegate> beansOfType = SpringUtil.getBeansOfType(BaseSubMessageDelegate.class);
        List<BaseSubMessageDelegate> values = new ArrayList<>(beansOfType.values());
        for (BaseSubMessageDelegate value : values) {
            MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(value);
            //设置序列化器，redis的值拿出来会多一个"， 导致json无法解析
            messageListenerAdapter.setSerializer(serializer);
            messageListenerAdapter.afterPropertiesSet();
            container.addMessageListener(messageListenerAdapter, ChannelTopic.of(value.getChannel()));
        }
        //启动监听容器
        container.start();
    }
}
